package com.snoopy.gas1.service.impl;

import com.snoopy.gas1.entity.Sales_record;
import com.snoopy.gas1.mapper.Sales_recordMapper;
import com.snoopy.gas1.service.SalesRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class Sales_recordServiceImpl implements SalesRecordService {
    @Autowired
    Sales_recordMapper salesRecordMapper;

    @Override
    public List<Sales_record> lists() {
        return salesRecordMapper.lists();
    }
//查询
    @Override
    public List<Sales_record> searchByCustomer(String customer) {
        if (customer == null || customer.trim().isEmpty()) {
            return salesRecordMapper.lists();
        } else {
            return salesRecordMapper.searchByCustomer(customer);
        }
    }

    @Override
    public void delete(int id) {
        if (id <= 0) {
            return;
        }
        salesRecordMapper.delete(id);
    }

    @Override
    public int add(Sales_record salesRecord) {
        Integer id = salesRecord.getId();
        // 校验id是否为空或非法
        if (id == null || id <= 0) {
            throw new RuntimeException("销售记录ID不能为空且必须为正数！");
        }
        // 校验id是否已存在
        Sales_record existing = salesRecordMapper.getById(id);
        if (existing != null) {
            throw new RuntimeException("销售记录ID已存在！");
        }
        return salesRecordMapper.add(salesRecord);
    }
    @Override
    public Sales_record getById(int id) {
        return salesRecordMapper.getById(id);
    }

    @Override
    public int update(Sales_record salesRecord) {
        // 1. 校验记录是否存在（不存在则抛异常）
        Sales_record existing = salesRecordMapper.getById(salesRecord.getId());
        if (existing == null) {
            throw new RuntimeException("记录不存在，无法更新");
        }
        // 2. 执行更新并校验结果
        int result = salesRecordMapper.update(salesRecord);
        if (result <= 0) {
            // 强制抛出异常，避免进入"不跳转"分支
            throw new RuntimeException("更新失败，影响行数为0");
        }
        return result;
    }

    @Override
    public List<Sales_record> getSalesRecords() {
        return salesRecordMapper.lists();
         // 需根据实际业务实现
    }

//    @Override
//    public void register(Sales_record salesRecord) {
//        salesRecordMapper.register(salesRecord);
//    }
}